#include "bsp/cpu_driver.h"
#include "os/os.h"
#include "led.h"

static u32 led_task(void *args);

void led_init(led_t *led, led_func handler) {
	if (led->handler == handler) {
		return;
	}
	led->handler = handler;
	led->ts_lastoff = 0;
	led->ts_laston = 0;
	led->on = false;
	led->on_duration = CONFIG_DEF_ON_DURATION;
	led->off_duration = CONFIG_DEF_OFF_DURATION;
	led->handler(led->on);
	os_task_create(led_task, led);
}

void led_set_duration(led_t *led, u32 on, u32 off) {
	led->on_duration = on;
	led->off_duration = off;
}

void led_on(led_t *led) {
	if (!led->on && os_delta_ms(led->ts_lastoff) >= led->off_duration) {
		led->on = true;
		led->ts_laston = os_timestemp();
		led->handler(led->on);
	}
}

void led_process(led_t *led) {
	if (led->on && os_delta_ms(led->ts_laston) >= led->on_duration) {
		led->on = false;
		led->ts_lastoff = os_timestemp();
		led->handler(led->on);
	}
}


static u32 led_task(void *args){
	led_t *led = (led_t *)args;
	led_process(led);
	return 0;
}

